package com.blogSystem.admin.filter;

import com.blogSystem.admin.pojo.Admin;
import com.fasterxml.jackson.databind.ObjectMapper;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import util.JwtUtil;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;


public class JWTLoginFilter extends UsernamePasswordAuthenticationFilter {
    @Autowired
    private JwtUtil jwtUtil;


    private AuthenticationManager authenticationManager;
    public JWTLoginFilter(AuthenticationManager authenticationManager){
        this.authenticationManager=authenticationManager;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        try {
            Admin admin=new ObjectMapper().readValue(request.getInputStream(),Admin.class);
            return authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(admin.getName(),admin.getPassword())
            );
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        long nowMillis=System.currentTimeMillis();
        String token = Jwts.builder()
                .setSubject(((Admin) authResult.getPrincipal()).getName())
                .setIssuedAt(new Date())
                .setExpiration(new Date(nowMillis+360000)) //设置有效期1小时
                .signWith(SignatureAlgorithm.HS512, "jwtSecurity")
                .compact();
        //将生成token返回给前台
        Result result=new Result();
        result.setCode(StatusCode.OK);
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.println(new Result(true,StatusCode.OK,"验证通过",authResult));
        out.flush();
        out.close();
    }

}
